﻿#!/usr/bin/env python2.5
# coding: UTF-8
'''
Created on 2011/04/21

@author: yang_wanjun
'''
import json

from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse
from django.db.models import Q
from django.contrib import messages
from django.contrib.comments import Comment 
from django.contrib.auth.admin import User
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import PasswordChangeForm
from django.utils.translation import ugettext as _
from senbzblog.blog.models import Article, Category, Link, Page
from senbzblog.blog import forms as blogforms
from senbzblog.utils import utils
from senbzblog.utils.utils import render_response
from senbzblog.comments.forms import ArticleCommentForm
from senbzblog.tags.models import Tag
#from senbzblog.settings import DATABASES

@login_required
def index(request, username):
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
    
    artilce_count = Article.admin_objects.filter(blog=user.bloginfo).count()
    category_count = Category.objects.filter(blog=user.bloginfo).count()
    comments = Comment.objects.filter(object_pk__in=
        Article.objects.filter(blog=blog).values('id')).order_by('-submit_date')
    comment_count = comments.count()
    spam_count = comments.filter(is_public=False).count()
    tag_count = Tag.objects.count()
    
    return render_response(request, 'admin/index.html', locals())

@login_required
def article(request, username):
    ctx = get_article_context(username)
    return render_response(request, 'admin/article.html', ctx)

@login_required
def article_quick_post(request, username):
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
    title = request.POST.get('title')
    contents = request.POST.get('content', '')
#    article_tags = request.POST.get('tags', '')
    save = request.POST.get('save')
    publish = request.POST.get('publish')
    category = Category.objects.get(blog=blog, title=u"默认分类", type=1)
    
    if not title and not contents:
        return HttpResponse(_("Please input title and content!"))
    
    #验证是否重名
    existedarticle = Article.admin_objects.filter(blog=blog, title=title)
    if existedarticle.count() > 0:
        return HttpResponse(_("Existed article name, Please input it again!"))
    
    article = Article(title=title, contents=contents, blog=blog, category=category)
    
    if save:
        article.is_published = False
        article.save()
        html = u"<p>文章已保存.&nbsp;<a href='%s'>编辑文章</a></p>" % (article.get_admin_edit_article_url())
    elif publish:
        article.is_published = True
        article.save()
        html = u"<p>文章已发布.&nbsp;<a href='%s' target='_blank'>查看文章</a></p>" % (article.get_absolute_url())
    return HttpResponse(html)

@login_required
def article_save(request, username):
    data = request.POST
    ctx = get_article_context(username)
    blog = ctx['blog']
    id = request.POST.get('id', '')
    is_published = False
    if request.POST.get('publish'):
        is_published = True
    elif request.POST.get('unpublish'):
        is_published = False
    else:
        is_published = bool(request.POST.get('is_published') == 'True')
    
    if id:
        article = get_object_or_404(Article, pk=id)
        articleform = blogforms.ArticleForm(data, instance=article, auto_id=True)
    else:
        articleform = blogforms.ArticleForm(data, auto_id=True)
    ctx.update({'articleform':articleform})
    
    if articleform.is_valid():
        article = articleform.save(commit=False)
        existed = Article.objects.filter(Q(blog=blog),
            Q(title=article.title) | Q(slug=article.slug))
        if id:
            existed = existed.exclude(id=id)
        if existed.count() > 0:
            messages.error(request, _('Existed article name or alias, Please input it again!'))
            return render_response(request, 'admin/article.html', ctx)
        else:
            article.is_published = is_published
            article.save()
            messages.success(request, _('Article saved successfully'))
            return HttpResponseRedirect(article.get_admin_edit_article_url())
    else:
        return render_response(request, 'admin/article.html', ctx)

@login_required
def article_delete(request, username, id):
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
    article = get_object_or_404(Article, pk=id)
    article.delete()
    
    #获取删除后要跳转到的页面
    nexturl = request.GET.get('nexturl')
    if not nexturl:
        nexturl = request.POST.get('nexturl')
    if nexturl:
        return HttpResponseRedirect(nexturl)
    else:
        return HttpResponseRedirect(blog.get_admin_show_articles_url())

@login_required
def articles_delete(request, username):
    #显示用户及博客信息
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
    try:
        allchecks = request.POST.getlist("checks")
        for id in allchecks:
            article = Article.admin_objects.get(pk=id)
            article.delete()
    finally:
        return HttpResponseRedirect(blog.get_admin_show_articles_url())

@login_required
def article_edit(request, username, slug):
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
    article = Article.admin_objects.get(blog=blog, slug=slug)
    ctx = get_article_context(username, article)
    return render_response(request, 'admin/article.html', ctx)

@login_required
def articles(request, username):
    #显示用户及博客信息
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
    #分页
    article_list = Article.admin_objects.filter(blog=blog)
    current_page = utils.get_current_page(request)
    pages_context = utils.get_pages_context(article_list, current_page, blog.display_count)
    articles = pages_context['page_current']
    articles_page_range = pages_context['page_range']
    
    all_count = article_list.count()
    published_count = Article.objects.filter(blog=blog).count()
    unpublish_count = all_count - published_count
    
    archives = Article.admin_objects.dates('created_date', 'month')
    categories = blog.get_article_categories()
    
    return render_response(request, 'admin/articles.html', locals())

@login_required
def articles_published(request, username):
    #显示用户及博客信息
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
    #分页
    article_list = Article.objects.filter(blog=blog)
    current_page = utils.get_current_page(request)
    pages_context = utils.get_pages_context(article_list, current_page, blog.display_count)
    articles = pages_context['page_current']
    articles_page_range = pages_context['page_range']
    
    all_count = Article.admin_objects.filter(blog=blog).count()
    published_count = article_list.count()
    unpublish_count = all_count - published_count
    archives = Article.admin_objects.dates('created_date', 'month')
    categories = blog.get_article_categories()
    
    return render_response(request, 'admin/articles.html', locals())

@login_required
def articles_unpublished(request, username):
    #显示用户及博客信息
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
    #分页
    article_list = Article.admin_objects.filter(blog=blog, is_published=False)
    current_page = utils.get_current_page(request)
    pages_context = utils.get_pages_context(article_list, current_page, blog.display_count)
    articles = pages_context['page_current']
    articles_page_range = pages_context['page_range']
    
    published_count = Article.objects.filter(blog=blog).count()
    unpublish_count = article_list.count()
    all_count = published_count + unpublish_count
    archives = Article.admin_objects.dates('created_date', 'month')
    categories = blog.get_article_categories()
    
    return render_response(request, 'admin/articles.html', locals())

@login_required
def pages(request, username):
    #显示用户及博客信息
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
    #分页
    page_list = Page.admin_objects.filter(blog=blog)
    current_page = utils.get_current_page(request)
    pages_context = utils.get_pages_context(page_list, current_page, 10)
    pages = pages_context['page_current']
    pages_page_range = pages_context['page_range']
    
    all_count = page_list.count()
    published_count = Page.objects.filter(blog=blog).count()
    unpublish_count = all_count - published_count
    
    return render_response(request, 'admin/pages.html', locals())

@login_required
def page_published(request, username):
    #显示用户及博客信息
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
    #分页
    page_list = Page.objects.filter(blog=blog)
    current_page = utils.get_current_page(request)
    pages_context = utils.get_pages_context(page_list, current_page, 10)
    pages = pages_context['page_current']
    pages_page_range = pages_context['page_range']
    
    all_count = Page.admin_objects.filter(blog=blog).count()
    published_count = page_list.count()
    unpublish_count = all_count - published_count
    
    return render_response(request, 'admin/pages.html', locals())

@login_required
def page_unpublished(request, username):
    #显示用户及博客信息
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
    #分页
    page_list = Page.admin_objects.filter(blog=blog, is_published=False)
    current_page = utils.get_current_page(request)
    pages_context = utils.get_pages_context(page_list, current_page, 10)
    pages = pages_context['page_current']
    pages_page_range = pages_context['page_range']
    
    all_count = Page.admin_objects.filter(blog=blog).count()
    unpublish_count = page_list.count()
    published_count = all_count - unpublish_count
    
    return render_response(request, 'admin/pages.html', locals())

@login_required
def page(request, username):
    ctx = get_page_context(username)
    return render_response(request, 'admin/page.html', ctx)

@login_required
def page_edit(request, username, slug):
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
    page = Page.admin_objects.get(blog=blog, slug=slug)
    ctx = get_page_context(username, page)
    return render_response(request, 'admin/page.html', ctx)

@login_required
def page_delete(request, username, slug):
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
    page = get_object_or_404(Page, blog=blog, slug=slug)
    page.delete()
    
    #获取删除后要跳转到的页面
    nexturl = request.GET.get('nexturl')
    if not nexturl:
        nexturl = request.POST.get('nexturl')
    if nexturl:
        return HttpResponseRedirect(nexturl)
    else:
        return HttpResponseRedirect(blog.get_admin_show_pages_url())

@login_required
def page_save(request, username):
    data = request.POST
    ctx = get_page_context(username)
    blog = ctx['blog']
    id = request.POST.get('id', '')
    
    # 判断是发布，还是保存草稿
    is_published = False
    if request.POST.get('publish'):
        is_published = True
    elif request.POST.get('unpublish'):
        is_published = False
    else:
        is_published = bool(request.POST.get('is_published') == 'True')
    
    # 判断是编辑还是添加
    if id:
        page = get_object_or_404(Page, pk=id)
        pageform = blogforms.PageForm(data, instance=page, auto_id=True)
    else:
        pageform = blogforms.PageForm(data, auto_id=True)
    ctx.update({'pageform':pageform})
    
    if pageform.is_valid():
        page = pageform.save(commit=False)
        existed = Page.objects.filter(Q(blog=blog),
            Q(title=page.title) | Q(slug=page.slug))
        if id:
            existed = existed.exclude(id=id)
        if existed.count() > 0:
            messages.error(request, _('Existed page name or alias, Please input it again!'))
            return render_response(request, 'admin/page.html', ctx)
        else:
            page.is_published = is_published
            page.save()
            messages.success(request, _('Page saved successfully'))
            
            # 获取排序顺序
            ordered_values = request.POST.get('ordered_values')
            if ordered_values:
                ordered_values = json.read(str(ordered_values))
                for index in ordered_values['orders']:
                    if int(index['value']) == 0:
                        page.order = index['order']
                        page.save()
                    else:
                        order_page = Page.admin_objects.get(pk=int(index['value']))
                        order_page.order = index['order']
                        order_page.save()

            return HttpResponseRedirect(page.get_admin_edit_page_url())
    else:
        return render_response(request, 'admin/page.html', ctx)

@login_required
def categories(request, username):
    ctx = get_categories_context(request, username)
    return render_response(request, 'admin/categories.html', ctx)

@login_required
def category_save(request, username):
    data = request.POST
    ctx = get_categories_context(request, username)
    blog = ctx['blog']
    id = request.POST.get('id')
    
    if id:
        categoryform = blogforms.CategoryForm(data, instance=get_object_or_404(Category, pk=id), auto_id=True)
    else:
        categoryform = blogforms.CategoryForm(data, auto_id=True)
    
    ctx.update({'categoryform':categoryform})
    
    if categoryform.is_valid():
        category = categoryform.save(commit=False)
        existed = Category.objects.filter(Q(blog=blog),
            Q(title=category.title) | Q(slug=category.slug))
        if id:
            existed = existed.exclude(id=id)
        if existed.count() > 0:
            messages.error(request, _('Existed category name, Please input it again!'))
            return render_response(request, 'admin/categories.html', ctx)
        else:
            category.save()
            messages.success(request, _('Category saved successfully'))
            
            # 获取排序顺序
            ordered_values = request.POST.get('ordered_values')
            if ordered_values:
                ordered_values = json.read(str(ordered_values))
                for index in ordered_values['orders']:
                    if int(index['value']) == 0:
                        category.order = index['order']
                        category.save()
                    else:
                        order_category = Category.objects.get(pk=int(index['value']))
                        order_category.order = index['order']
                        order_category.save()

            return HttpResponseRedirect(category.get_admin_show_category_url())
    else:
        return render_response(request, 'admin/categories.html', ctx)

@login_required
def category(request, username, slug):
    ctx = get_categories_context(request, username)
    blog = ctx['blog']
    category = get_object_or_404(Category, blog=blog, slug=slug)
    categoryform = blogforms.CategoryForm(instance=category, auto_id=False)
    ctx.update({'categoryform':categoryform, 'id':category.id})

    return render_response(request, 'admin/categories.html', ctx)

@login_required
def category_delete(request, username):
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
    if request.method == 'POST':
        action = request.POST.get('action', '')
        checks = request.POST.getlist('checks')
        if checks and action == 'delete':
            for id in checks:
                if id:
                    category = Category.objects.get(pk=id)
                    category.delete()
        return HttpResponseRedirect(blog.get_admin_show_categories_url())

@login_required
def media(request, username):
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
    return render_response(request, 'admin/media.html', locals())

#@login_required
#def media_backup_db(request, username):
#    defaultdb = DATABASES.get('default')
#    engine = defaultdb.get('ENGINE')
#    dbname = defaultdb.get('NAME')
##    if engine == 'django.db.backends.sqlite3':
#    return HttpResponseRedirect('/admin/%s/media' % username)

@login_required
def comments(request, username):
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
#    ctype = ContentType.objects.get_for_model(Article)
    comments = Comment.objects.filter(object_pk__in=
        Article.objects.filter(blog=blog).values('id'), is_public=True).order_by('-submit_date')
    comment_count = comments.count()
    spam_count = Comment.objects.filter(object_pk__in=
        Article.objects.filter(blog=blog), is_public=False).count()
    return render_response(request, 'admin/comments.html', locals())

@login_required
def comments_spam(request, username):
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
#    ctype = ContentType.objects.get_for_model(Article)
    comments = Comment.objects.filter(object_pk__in=
        Article.objects.filter(blog=blog).values('id'), is_public=False).order_by('-submit_date')
    spam_count = comments.count()
    comment_count = Comment.objects.filter(object_pk__in=
        Article.objects.filter(blog=blog), is_public=True).count()
    return render_response(request, 'admin/comments.html', locals())

@login_required
def comments_delete(request, username):
    next = request.POST.get('next')
    try:
        allchecks = request.POST.getlist("checks")
        for id in allchecks:
            c = Comment.objects.get(pk=id)
            c.delete()
    finally:
        if next:
            return HttpResponseRedirect(next)
        else:
            return HttpResponseRedirect('/admin/%s/comments.html' % username)

@login_required
def comment_delete(request, username, id):
    next = request.GET.get('next')
    try:
        c = Comment.objects.get(pk=id)
        c.delete()
    finally:
        if next:
            return HttpResponseRedirect(next)
        else:
            return HttpResponseRedirect('/admin/%s/comments.html' % username)

@login_required
def comment_edit(request, username, id):
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
    comment = get_object_or_404(Comment, pk=id)
    commentform = ArticleCommentForm(instance=comment, auto_id=True)
    return render_response(request, 'admin/comment.html', locals())

@login_required
def comment_save(request, username, id):
    data = request.POST
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
    id = request.POST.get('id')
    comment = get_object_or_404(Comment, pk=id)
    commentform = ArticleCommentForm(data, instance=comment, auto_id=True)
    if commentform.is_valid():
        commentform.save()
        return HttpResponseRedirect('/admin/%s/comments.html' % username)
    else:
        return render_response(request, 'admin/comment.html', locals())

@login_required
def comment_to_spam(request, username, id):
    next = request.GET.get('next')
    approve = request.GET.get('approve')
    comment = get_object_or_404(Comment, pk=id)
    if int(approve) == 0:
        comment.is_public = False
    else:
        comment.is_public = True
    comment.save()
    if next:
        return HttpResponseRedirect(next)
    else:
        return HttpResponseRedirect('/admin/%s/comments.html' % username)

@login_required
def links(request, username):
    ctx = get_links_context(request, username)
    return render_response(request, 'admin/links.html', ctx)

@login_required
def link(request, username, id):
    ctx = get_links_context(request, username)
    link = get_object_or_404(Link, pk=id)
    id = link.id
    linkform = blogforms.LinkForm(instance=link, auto_id=False)
    ctx.update({'linkform':linkform, 'id':id})
    return render_response(request, 'admin/links.html', ctx)

@login_required
def link_save(request, username):
    data = request.POST
    ctx = get_links_context(request, username)
    blog = ctx["blog"]
    id = request.POST.get('id')
    if id:
        linkform = blogforms.LinkForm(data, instance=get_object_or_404(Link, pk=id), auto_id=True)
    else:
        linkform = blogforms.LinkForm(data, auto_id=True)
    
    ctx.update({'linkform':linkform})
    if linkform.is_valid():
        link = linkform.save(commit=False)
        #验证是否重名
        existedlink = Link.objects.filter(Q(blog=blog), Q(title=link.title) | Q(link_url=link.link_url))\
            .exclude(id=link.id)
        if existedlink.count() > 0:
            messages.error(request, _('Existed link, Please input it again!'))
            return render_response(request, 'admin/links.html', ctx)
        if not link.link_url.startswith("http://") and not link.link_url.startswith("https://"):
            link.link_url = "http://" + link.link_url
        link.blog = blog
        link.save()
        messages.success(request, _('Link saved successfully'))
        return HttpResponseRedirect(blog.get_admin_links_url())
    else:
        return render_response(request, 'admin/links.html', ctx)
    
    ctx.update({'link':link})
    
@login_required
def links_delete(request, username):
    try:
        allchecks = request.POST.getlist("checks")
        for id in allchecks:
            c = Link.objects.get(pk=id)
            c.delete()
    finally:
        return HttpResponseRedirect('/admin/%s/links.html' % username)

@login_required
def users(request, username):
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
    return render_response(request, 'admin/users.html', locals())

@login_required
def user(request, username):
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
    
    userform = blogforms.UserChangeForm(instance=user, auto_id=True)
    try:
        profileform = blogforms.ProfileForm(instance=user.get_profile(), auto_id=True)
    except:
        profileform = blogforms.ProfileForm(auto_id=True)
    return render_response(request, 'admin/profile.html', locals())

@login_required
def user_save(request, username):
    data = request.POST
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
    file = None
    if request.FILES:
        file = request.FILES['image_url']
    
    userform = blogforms.UserChangeForm(data, instance=user, auto_id=True)
    try:
        profileform = blogforms.ProfileForm(data, request.FILES, instance=user.get_profile(), auto_id=True)
    except:
        profileform = blogforms.ProfileForm(data, request.FILES, auto_id=True)
    if profileform.is_valid() and userform.is_valid():
        userform.save()
        if file:
            profilemodel = profileform.save(commit=False)
            profilemodel.image_url = '/%s/portrait.jpeg' % username
            profilemodel.save()
        else:
            profileform.save()
        messages.success(request, _('saved successfully!'))
        return HttpResponseRedirect(blog.get_admin_profile_url())
    else:
        return render_response(request, 'admin/profile.html', locals())


def user_change_password(request, username):
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
    if request.POST:
        passwordform = PasswordChangeForm(user, request.POST, auto_id=True)
        if passwordform.is_valid():
            passwordform.save()
            messages.success(request, _('Password changed successfully!'))
        else:
            return render_response(request, 'admin/changepassword.html', locals())
        
    passwordform = PasswordChangeForm(user, auto_id=True)
    return render_response(request, 'admin/changepassword.html', locals())

@login_required
def settings(request, username):
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
    blogform = blogforms.BlogForm(instance=blog, auto_id=True)
    return render_response(request, 'admin/settings.html', locals())

@login_required
def settings_save(request, username):
    data = request.POST
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
    blogform = blogforms.BlogForm(data, instance=blog, auto_id=True)
    if blogform.is_valid():
        blog.save()
        messages.success(request, _('settings saved successfully!'))
    return render_response(request, 'admin/settings.html', locals())

@login_required
def tags(request, username):
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
    tag_list = Tag.objects.all()
    current_page = utils.get_current_page(request)
    pages_context = utils.get_pages_context(tag_list, current_page, 10)
    tags = pages_context['page_current']
    tags_page_range = pages_context['page_range']
    
    return render_response(request, 'admin/tags.html', locals())

def get_article_context(username, article=None):
    #显示用户及博客信息
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
    categories = Category.objects.filter(blog=blog)
    if article:
        articleform = blogforms.ArticleForm(instance=article, auto_id=True)
        return locals()
    else:
        category = Category.objects.get(blog=blog, title=u'默认分类')
        articleform = blogforms.ArticleForm(initial={'blog':blog, 'category':category}, auto_id=True)
        return locals()

def get_page_context(username, page=None):
    #显示用户及博客信息
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
    order = Page.admin_objects.filter(blog=blog).count()
    pages = Page.admin_objects.filter(blog=blog)
    if page:
        page.order = order
        current_page = page.id
        pageform = blogforms.PageForm(instance=page, auto_id=True)
        return locals()
    else:
        order = order + 1
        current_page = 0
        pageform = blogforms.PageForm(initial={'blog':blog, 'order':order}, auto_id=True)
        return locals()

def get_categories_context(request, username):
    #显示用户及博客信息
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
    #分页
    category_list = blog.get_article_categories()
    current_page = utils.get_current_page(request)
    pages_context = utils.get_pages_context(category_list, current_page, 10)
    categories = pages_context['page_current']
    categories_page_range = pages_context['page_range']
    order = Category.objects.filter(blog=blog).count()
    categoryform = blogforms.CategoryForm(initial={'blog':blog, 'order':order + 1}, auto_id=True)
    ctx = {'user': user, 'blog':blog, 'category_list':category_list,
           'categories':categories, 'categories_page_range':categories_page_range,
           'categoryform':categoryform}
    return ctx

def get_links_context(request, username):
    user = get_object_or_404(User, username=username)
    blog = user.bloginfo
    current_page = utils.get_current_page(request)
    link_list = Link.objects.filter(blog=blog)
    pages_context = utils.get_pages_context(link_list, current_page, 10)
    links = pages_context['page_current']
    links_page_range = pages_context['page_range']
    linkform = blogforms.LinkForm(auto_id=True)
    ctx = {'user':user, 'blog':blog, 'links':links,
           'links_page_range':links_page_range, 'linkform':linkform}
    return ctx
